package com.java.service.impl;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import com.java.dao.AdvertiserMapper;
import com.java.dao.ApplyMapper;
import com.java.dao.IndexMapper;
import com.java.dao.MediaMapper;
import com.java.model.*;
import com.java.service.IndexService;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private IndexMapper indexMapper;

    @Autowired
    private AdvertiserMapper advertiserMapper;

    @Autowired
    private ApplyMapper applyMapper;

    @Autowired
    private MediaMapper mediaMapper;
    int yanzheng = 0;
    //广告主登录
    @Override
    public Result login(Account account, HttpServletRequest request, Model model) {
        Account acc = indexMapper.login(account);
        Account phone = indexMapper.CheckPhone(account.getPhoneNum());
        if (acc!=null){
            request.getSession().setAttribute("account",acc);
            return Result.success();
        }if (phone == null || phone.equals("")){
            return Result.error("该手机号尚未注册，请先注册");
        }
        return Result.error("用户名或密码错误");
    }

//    @Override
//    public List<Media> list(Media media) {
//        return null;
//    }

    @Override
    public Result register(String phoneNum,HttpServletRequest request,Account account) {
        Account checkPhone = indexMapper.CheckPhone(account.getPhoneNum());
        if (checkPhone == null || checkPhone.equals("")){
            // 获取验证码
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId("LTAI5t7wwXaPkgZkqN9hzQ6q")
                    .accessKeySecret("9GIpIv4zQ08BCUAQwJqil0zhj6Z93r")
                    //.securityToken("<your-token>") // use STS token
                    .build());
            // Configure the Client
            AsyncClient client = AsyncClient.builder()
                    .region("cn-hangzhou") // Region ID
                    //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                    .credentialsProvider(provider)
                    //.serviceConfiguration(Configuration.create()) // Service-level configuration
                    // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    .setEndpointOverride("dysmsapi.aliyuncs.com")
                            //.setConnectTimeout(Duration.ofSeconds(30))
                    )
                    .build();

            for(int j = 0; j< 100; j++){
                yanzheng = (int)((Math.random()*9+1)*100000);
            }
            // Parameter settings for API request
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName("阿里云短信测试")
                    .templateCode("SMS_154950909")
                    .phoneNumbers(phoneNum)
                    .templateParam("{\"code\":\""+yanzheng+"\"}")
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            // Synchronously get the return value of the API request
            SendSmsResponse resp = null;
            try {
                resp = response.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            System.out.println(new Gson().toJson(resp));
            client.close();

            //获取验证码
            String templateParam = sendSmsRequest.getTemplateParam();
            request.getSession().setAttribute("templateParam", templateParam);
            System.out.println(templateParam);
            return Result.success();
        }else {
            return Result.error("手机号已存在，请更换手机号");
        }
    }
    //注册校验验证码是否正确
    @Override
    public Result CheckCode(Account account) {
        if (account.getVerification().equals(yanzheng+"")) {
            indexMapper.register(account);
            indexMapper.wallet(account);
            return Result.success();
        }
        return Result.error("验证码输入有误");
    }

    //忘记密码校验验证码是否正确
    @Override
    public Result CheckCode2(Account account) {
        if (account.getVerification().equals(yanzheng+"")) {
            indexMapper.updatePwd(account);
            return Result.success();
        }
        return Result.error("验证码输入有误");
    }

    @Override
    public Result forget(String phoneNum, HttpServletRequest request, Account account) {
        Account checkPhone = indexMapper.CheckPhone(account.getPhoneNum());
        if (checkPhone == null || checkPhone.equals("")){
          return Result.error("该手机号尚未注册，请先注册");
        }else {
            // 获取验证码
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId("LTAI5tGYg162Fc6SbFrpahoP")
                    .accessKeySecret("gcBDEVEPAghvSRkXhDiHuneJk2LIQc")
                    //.securityToken("<your-token>") // use STS token
                    .build());
            // Configure the Client
            AsyncClient client = AsyncClient.builder()
                    .region("cn-hangzhou") // Region ID
                    //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                    .credentialsProvider(provider)
                    //.serviceConfiguration(Configuration.create()) // Service-level configuration
                    // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    .setEndpointOverride("dysmsapi.aliyuncs.com")
                            //.setConnectTimeout(Duration.ofSeconds(30))
                    )
                    .build();

            for(int j = 0; j< 100; j++){
                yanzheng = (int)((Math.random()*9+1)*100000);
            }
            // Parameter settings for API request
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName("阿里云短信测试")
                    .templateCode("SMS_154950909")
                    .phoneNumbers(phoneNum)
                    .templateParam("{\"code\":\""+yanzheng+"\"}")
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            // Synchronously get the return value of the API request
            SendSmsResponse resp = null;
            try {
                resp = response.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            System.out.println(new Gson().toJson(resp));
            client.close();

            //获取验证码
            String templateParam = sendSmsRequest.getTemplateParam();
            request.getSession().setAttribute("templateParam", templateParam);
            System.out.println(templateParam);
            return Result.success();
        }
    }

    @Override
    public Result forgetMedia(String phoneNum, HttpServletRequest request, Account account) {
        Account checkPhone = indexMapper.CheckPhone2(account.getPhoneNum());
        if (checkPhone == null || checkPhone.equals("")){
            // 获取验证码
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId("LTAI5tGYg162Fc6SbFrpahoP")
                    .accessKeySecret("gcBDEVEPAghvSRkXhDiHuneJk2LIQc")
                    //.securityToken("<your-token>") // use STS token
                    .build());
            // Configure the Client
            AsyncClient client = AsyncClient.builder()
                    .region("cn-hangzhou") // Region ID
                    //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                    .credentialsProvider(provider)
                    //.serviceConfiguration(Configuration.create()) // Service-level configuration
                    // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    .setEndpointOverride("dysmsapi.aliyuncs.com")
                            //.setConnectTimeout(Duration.ofSeconds(30))
                    )
                    .build();

            for(int j = 0; j< 100; j++){
                yanzheng = (int)((Math.random()*9+1)*100000);
            }
            // Parameter settings for API request
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName("阿里云短信测试")
                    .templateCode("SMS_154950909")
                    .phoneNumbers(phoneNum)
                    .templateParam("{\"code\":\""+yanzheng+"\"}")
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .build();

            // Asynchronously get the return value of the API request
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            // Synchronously get the return value of the API request
            SendSmsResponse resp = null;
            try {
                resp = response.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            System.out.println(new Gson().toJson(resp));
            client.close();

            //获取验证码
            String templateParam = sendSmsRequest.getTemplateParam();
            request.getSession().setAttribute("templateParam", templateParam);
            System.out.println(templateParam);
            return Result.success();

        }else {
            return Result.error("该手机号已存在，请更换手机号");
        }
    }

    @Override
    public Result updatePwd(Account account) {
        if (account.getVerification().equals(yanzheng+"")) {
            indexMapper.updatePwd(account);
            return Result.success();
        }
        return Result.error("验证码输入有误");
    }

    @Override
    public Account Personal(int id, HttpServletRequest request, Model model) {
        Account personal = indexMapper.personal(id);
        return personal;
    }

    @Override
    public Advertiser balance(int id, HttpServletRequest request, Model model) {
        Advertiser advertiser = new Advertiser();
        advertiser.setId(id);
        Advertiser list =  advertiserMapper.bList(advertiser);
        return list;
    }

    @Override
    public Result recharge(int id, Double amount) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("amount", amount);
        advertiserMapper.cList(map);
        advertiserMapper.dList(map);
        return Result.success();
    }

    @Transactional
    @Override
    public Result modify(Account account) {
        indexMapper.modify(account);
        return Result.success();
    }

    @Override
    public Result get(int id) {
        Account account = indexMapper.get(id);
        return Result.success(account,null);
    }
    @Override
    public List<Classify> listApply(Classify classify) {
        List<Classify> list = indexMapper.list();
        return list;
    }

    @Override
    public Result apply(Apply apply) {
        Account many = indexMapper.many(apply.getAdsId());
        Double availableBalance = many.getFinance().getAvailableBalance();
//        System.out.println(apply.getPrice());
        if (apply.getPrice() <= availableBalance){
            //余额足够的情况下，投放价格=冻结金额，新增申请到自媒体审核
            apply.setStatus(1);
            applyMapper.blist(apply);
            applyMapper.upMany(apply);
            applyMapper.save(apply);
            return Result.success();
        }
        return Result.error("您的余额不足，请先充值");
    }

}
